import { UserChannelResponse, AllChannelsResponse, Channel } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import { http } from '@/utils'

import { differenceBy } from 'lodash'

// 获取我的频道
export const getUserChannel = (): RootThunkAction => {
  return async (dispatch) => {
    const res: UserChannelResponse = await http.get('/user/channels')
    const { channels } = res.data
    console.log('频道列表：', channels)
    dispatch({ type: 'home/getUserChannel', payload: channels })
  }
}
// 获取所有频道
export const getAllChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    const res: AllChannelsResponse = await http.get('channels')
    const {
      home: { userChannel },
    } = getState()
    const restChannels = differenceBy(res.data.channels, userChannel, 'id')

    dispatch({ type: 'home/getAllChannel', payload: restChannels })
  }
}

// 删除我的频道
export const delChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    await http.delete(`/user/channels/${channel.id}`)
    // 更新状态
    dispatch({ type: 'home/delChannel', payload: channel })
  }
}

// 添加我的频道
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    await http.patch('/user/channels', { channels: [channel] })
    // 更新状态
    dispatch({ type: 'home/addChannel', payload: channel })
  }
}
